using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using CE.User;
using CE.Global;
using CE.Provider;
using CE.Mail;
using CE.Company;
using CE.Configuration;

public partial class Admin_provider_AddNewProvider : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.UserTypeId] != null)
        {
            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.SiteAdmin))
            {
                Response.Redirect("AdminSecureLogin.aspx");
            }
        }
        else
        {
            Response.Redirect("AdminSecureLogin.aspx");
        }

        if (!IsPostBack)
        {
            DataTable _dtCompany = General.GetComboItem("TH.ProviderCompany", false);
            ddlProviderCompany.DataSource = _dtCompany;
            ddlProviderCompany.DataTextField = _dtCompany.Columns[0].ColumnName.ToString();
            ddlProviderCompany.DataValueField = _dtCompany.Columns[1].ColumnName.ToString();
            ddlProviderCompany.DataBind();

            //usrOccupation1.IsEnableValidation(true);
            //UsrGender1.IsEnableValidation(true);
            //usrIdNumber1.IsEnableValidation(true);
            //usrIdType1.IsEnableValidation(true);
            //UsrNationality1.IsEnableValidation(true);
        }
    }
    protected void btnAddNew_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "";
        Page.Validate();
        if (IsValid)
        {
            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();
            if (_useraccountdb.IsAlreadyExist(txtEmailAddress.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Provider)))
            {
                lblMessage.Text = "Email address is already exists!";
                lblMessage.ForeColor = System.Drawing.Color.Red;
                txtEmailAddress.Focus();
                return;
            }
            else
            {
                Profile _userprofile = new Profile();
                ProfileDB _userprofiledb = new ProfileDB();
                Contact _contact = new Contact();
                ContactDB _contactdb = new ContactDB();

                long _result = -1;

                _useraccount.Email = txtEmailAddress.Text;

                Random _random = new Random();
                //Two Upper, two lower of Company Name and 4 ramdom numbers
                string _authcode = ddlProviderCompany.SelectedItem.Text.Substring(0, 2).ToUpper();
                if (ddlProviderCompany.SelectedItem.Text.Length > 3)
                {
                    _authcode += ddlProviderCompany.SelectedItem.Text.Substring(2, 2).ToLower();
                }
                else
                {
                    _authcode += "pw";
                }
                _authcode += _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();

                _useraccount.AuthCode = txtAuthCode.Text;   //_authcode; 
                _useraccount.AuthHint = "NEW PROVIDER";
                _useraccount.UserId = "CEUSERAUTOIDPRO";
                _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Provider);
                _useraccount.IsAcceptTC = true;
                _useraccount.Status = true;
                _useraccount.RefCEUserID = Convert.ToInt64(Session[General.UserId].ToString());

                _result = _useraccountdb.Insert(_useraccount);
                _useraccount.CEID = _result;

                if (_result > 0)
                {
                    _userprofile.Salutation = UsrSalutation1.GetSalutation();
                    _userprofile.FirstName = txtFirstName.Text;
                    _userprofile.SurName = txtSurName.Text;
                    _userprofile.DOB = UsrDate1.GetDate();
                    _userprofile.Gender = Convert.ToChar(UsrGender1.GetGender());
                    _userprofile.MaritalStatus = Convert.ToInt32(ddlMaritalStatus.SelectedValue);
                    _userprofile.OccupationType = Convert.ToInt32(ddlOccupationType.SelectedValue);
                    _userprofile.Occupation = Convert.ToInt32(usrOccupation1.GetOccupation());

                    _userprofile.IDType = usrIdType1.GetIDType();
                    _userprofile.IDNo = usrIdNumber1.GetIdNumber();
                    _userprofile.HighEducation = txtHighEducation.Text;
                    _userprofile.Nationality = UsrNationality1.GetNationality();
                    _userprofile.RefCEUserId = _useraccount.CEID;
                    _userprofile.Info1 = ddlProviderCompany.SelectedValue;
                    _userprofile.Info2 = ddlProviderCompany.SelectedItem.Text;
                    _userprofile.Status = "NEW";
                    _result = _userprofiledb.Insert(_userprofile);


                    _contact.Mobile = txtMobileNo.Text;
                    _contact.Email = _useraccount.Email;
                    _contact.HomePhone = txtHomePhoneNo.Text;
                    //_contact.HomeFax = txtHomeFaxNo.Text;
                    //_contact.HomeUnitNo1 = txtHomeUnitNo1.Text;
                    //_contact.HomeUnitNo2 = txtHomeUnitNo2.Text;
                    //_contact.HomeStreet = txtHomeStreet.Text;
                    //_contact.HomeCity = txtHomeCity.Text;
                    //_contact.HomeCountry = ddlHomeCountry.Text;
                    //_contact.HomePostCode = txtHomePostCode.Text;

                    _contact.OfficePhone = txtOfficeNo.Text;
                    _contact.OfficeFax = txtOfficeFaxNo.Text;
                    _contact.OfficePhone = txtOfficeNo.Text;
                    //_contact.OfficeUnitNo2 = txtOfficeUnitNo2.Text;
                    _contact.OfficeStreet = txtOfficeStreet.Text;
                    _contact.OfficeCity = txtOfficeCity.Text;
                    _contact.OfficeCountry = ddlOfficeCountry.Text;
                    _contact.OfficePostCode = txtOfficePostCode.Text;
                    _contact.Status = true;
                    _contact.RefCEUserId = _useraccount.CEID;
                    _result = _contactdb.Insert(_contact);

                    ProviderCompanyLink _procomlink = new ProviderCompanyLink();
                    ProviderCompanyLinkDB _procomlinkdb = new ProviderCompanyLinkDB();

                    _procomlink.ProviderCompanyId = Convert.ToInt64(ddlProviderCompany.SelectedValue);
                    _procomlink.CEID = _useraccount.CEID;
                    _procomlink.UpdateFlage = false;

                    _procomlinkdb.Insert(_procomlink);

                    string _username = txtSurName.Text;
                    if (txtFirstName.Text.Length > 0)
                    {
                        _username += " " + txtFirstName.Text;
                    }

                    if (_result > 0)
                    {
                        #region "send email"                        
                        //if (!SendMailToUser(txtEmailAddress.Text, _username, _authcode))
                        //{
                        //    _useraccount.Info1 = "0";
                        //    _useraccount.Info2 = "New User - Provider";
                        //    _useraccountdb.Insert(_useraccount);
                        //    lblMessage.Text = "Adding new provider is succeeded.<br />Email can't be sent.";
                        //    lblMessage.ForeColor = System.Drawing.Color.Red;
                        //}
                        //else
                        //{
                        //    lblMessage.Text = "Adding new provider is succeeded.";
                        //    lblMessage.ForeColor = System.Drawing.Color.Green;
                        //}
                        #endregion

                        lblMessage.Text = "Adding new provider is succeeded.";
                        lblMessage.ForeColor = System.Drawing.Color.Green;

                    }
                    else
                    {
                        lblMessage.Text = "Adding new provider is failed.";
                        lblMessage.ForeColor = System.Drawing.Color.Red;
                    }
                }
            }
        }
        else
        {
            lblMessage.Text = "Not Valid";
            lblMessage.ForeColor = System.Drawing.Color.Red;
        }
    }

    protected void btnClearForm_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "Ready";
        lblMessage.ForeColor = System.Drawing.Color.Blue;
        txtEmailAddress.Text = "";
        txtAuthCode.Text = "";
        txtAuthCodeConfirm.Text = "";
        txtFirstName.Text = "";
        txtSurName.Text = "";
        txtHighEducation.Text = "";
        txtHomePhoneNo.Text = "";
        txtMobileNo.Text = "";
        txtOfficeNo.Text = "";
        txtOfficeFaxNo.Text = "";
        txtOfficePostCode.Text = "";
        txtOfficeStreet.Text = "";
        txtOfficeCity.Text = "";
        txtOfficeUnitNo1.Text = "";
        txtOfficeUnitNo2.Text = "";
        ddlOfficeCountry.SelectedIndex = 0;
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Admin/AdminHome.aspx");
    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        Response.Redirect("AssignProviderType.aspx");
    }

    private bool SendMailToUser(string EmailAddress, string UserName, string DummyAuthCode)
    {
        bool _retVal = false;
        //MyMailManager _mailMgr = new MyMailManager();

        string _mailBody = "";
        string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();
        string imgLogoUrl = _currentDomainUrl + CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LogoPath");
        CompanyInformation _company = new CompanyInformation();
        CompanyInformationDB _companydb = new CompanyInformationDB();
        _company = _companydb.GetCompanyInformation(3);
        string _companyAddress = "";
        string _emailaddress = "";
        string _websiteaddress = "";
        if (_company != null)
        {
            _companyAddress = _company.Address1;
            _emailaddress = _company.EmailAddress;
            _websiteaddress = _company.Website;
        }
        _company = null;
        _companydb = null;

        _mailBody = "Dear " + UserName + ", <br /><br />Your CompareXpress user account has been created.";
        _mailBody += "<br /><br />You may now log in to <a href='https://www.comparexpress.com/provider/providersecurelogin.aspx' target='_blank'>https://www.comparexpress.com/provider/providersecurelogin.aspx</a> using the following username and password:";
        _mailBody += "<br /><br /> User Name : " + EmailAddress;
        _mailBody += "<br /> Password : " + DummyAuthCode;
        _mailBody += "<br /><br />You will need to change the password immediately when you login for the first time.";
        _mailBody += "<br /><br />If you have any questions, comments, or feedback, please do not hesitate to contact us at <a href='mailto:support@comparexpress.com'>support@comparexpress.com</a>.";
        _mailBody += "<br /><br />Best Regards,<br /><br />Your CompareXpress Team<br/>Customer Support - SG/International";
        _mailBody += "<br /><img src='" + imgLogoUrl + "' />";
        _mailBody += "<br /><hr />";
        _mailBody += _companyAddress;
        _mailBody += "<br /><a href='" + _websiteaddress + "' target='_blank'>" + _websiteaddress + "</a> :: <a href='mailto:" + _emailaddress + "' target='_blank'>" + _emailaddress + "</a><br /><hr />";
        _mailBody += "<br /><i>This is a computer-generated email. Please do not reply to this email.</i>";

        if (MyMailManager.SendCRMMessage(txtEmailAddress.Text, "Welcome to CompareXpress", _mailBody))
        {
            _retVal = true;
        }
        else
        {
            _retVal = false;
        }

        return _retVal;
    }
}